package com.huazai.juc.cec.thread.july.thirtyOne;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * @author Seon
 * @date 2022/7/31 17:01
 */
@Slf4j
public class ExerciseSell {
    public static void main(String[] args) {
        // 模拟多人买票


        TicketWindow ticketWindow = new TicketWindow(5000);

        List<Integer> list = new Vector<>();

        List<Thread> threadList = new ArrayList<>();

        for (int i = 0; i < 2000; i++) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
            Thread thread = new Thread(() -> {
                // 卖票
                int sold = ticketWindow.sell(randomAmount());
                list.add(sold);
            });
            threadList.add(thread);
            thread.start();
        }


        threadList.forEach(thread -> {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
                throw new RuntimeException();
            }
        });

        int sum;
        // 统计票数
        log.info("余票数量{}", ticketWindow.getCount());

        sum = list.stream().mapToInt(amount -> amount).sum();
        log.info("总共卖出了{}", sum);
    }

    private static Random random = new Random();

    public static int randomAmount() {
        return random.nextInt(2) + 1;
    }
}
